import { Request, Response, NextFunction } from "express";
import util from 'util'
export function resHandler(req: Request, res, next: NextFunction) {
  res.sendRes = ({ code = 200, data = null, success = true, message = 'success' }) => {
    res.type('application/json; charset=utf-8');
    res.status(code).send({
      code,
      data,
      success,
      message
    })
  }
  res.sendErr = ({ code = 500, data = null, success = false, message = '未知错误' }) => {
    res.type('application/json; charset=utf-8');
    res.status(code).send({
      code,
      data,
      success,
      message
    })
  }
  next()
}

export function errHandler(error: Error, req: Request, res, next: NextFunction) {
  if (error) {
    res.sendErr({
      code: 500,
      message: util.format(error) || '未知错误'
    })
    return
  }
  next()
}